package com.bdq.common.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.bdq.common.constants.Constant;
import com.bdq.common.entity.WechatMiniProgramTokenResponse;

import java.util.concurrent.TimeUnit;

/**
 * @author malei
 * @date 2024-05-03 11:48
 */
public class WechatMiniProgramUtil {

    /**
     * 获取Token
     *
     * @return
     */
    public static String getToken(){
        return RedisUtil.get(Constant.RedisKey.WECHAT_MINI_PROGRAM_TOKEN);
    }

    public static String createToken(String appId, String appSecret) {
        HttpResponse response = HttpRequest.get(String.format(Constant.WECHAT_TOKEN_REQUEST, appId, appSecret)).execute();
        WechatMiniProgramTokenResponse tokenResponse = JSON.parseObject(response.body(), WechatMiniProgramTokenResponse.class);
        RedisUtil.setExpire(Constant.RedisKey.WECHAT_MINI_PROGRAM_TOKEN, tokenResponse.getAccessToken(), (tokenResponse.getExpiresIn() - 60 * 10), TimeUnit.SECONDS);
        return RedisUtil.get(Constant.RedisKey.WECHAT_MINI_PROGRAM_TOKEN);
    }
}
